import 'package:excel_utils/pages/view/calendar_view.dart';
import 'package:excel_utils/pages/week/bean/RincosBean.dart';
import 'package:excel_utils/pages/week/week_entry/child/rincos/bloc/rincos_cubit.dart';
import 'package:excel_utils/repository/week/rincos_repository.dart';
import 'package:excel_utils/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class RincosPage extends StatefulWidget {
  const RincosPage({super.key});

  @override
  State<RincosPage> createState() => _RincosPageState();
}

class _RincosPageState extends State<RincosPage> {
  RincosCubit? rincosCubit;
  bool saveLoading = false;
  bool searchLoading = false;
  List<RincosBean> rincosData = [];
  Set<String> deleteIdData = {};

  String rincosStartDate = "";
  String rincosEndDate = "";
  int year = 2025;
  int month = 09;
  int day = 04;

  @override
  void initState() {


    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<RincosCubit>(
      create: (BuildContext context) {
        return RincosCubit(context.read<RincosRepository>());
      },
      child: BlocBuilder<RincosCubit, RincosState>(
        builder: (BuildContext context, RincosState state) {
          rincosCubit = rincosCubit ?? context.read<RincosCubit>();

          if (state is RincosInitial) {
          } else if (state is RincosDataLoading) {
            searchLoading = true;
          } else if (state is RincosDataSuccessState) {
            searchLoading = false;
            rincosData = state.rincosData;
          } else if (state is RincosDataFailureState) {
            searchLoading = false;
          } else if (state is RincosDeleteLoading) {
            deleteIdData.add(state.rincosId);
          } else if (state is RincosDeleteSuccessState) {
            deleteIdData.remove(state.rincosId);
          } else if (state is RincosDeleteFailureState) {
            deleteIdData.remove(state.rincosId);
          } else if (state is RincosSaveLoading) {
            saveLoading = true;
          } else if (state is RincosSaveSuccessState) {
            saveLoading = false;
            rincosData = state.rincosData;
          }

          return buildUI();
        },
      ),
    );
  }

  Widget buildUI() {
    return Container(
      child: Column(
        children: [
          Row(
            children: [
              CalendarView(
                onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                  rincosStartDate = "${startStr}";
                  rincosEndDate = "${endStr}";
                },
                onDateStartChanged: (startDateTime, startStr) {
                  print("disMonthFeeStartDate: $startDateTime, $startStr");
                  rincosStartDate = "${startStr}";
                },
                onDateEndChanged: (endDateTime, endStr) {
                  print("disMonthFeeEndDate: $endDateTime, $endStr");
                  rincosEndDate = "${endStr}";
                },
              ),
              searchLoading
                  ? CircularProgressIndicator()
                  : ElevatedButton(
                      onPressed: () {
                        rincosCubit?.getRincos(maps: {"startDate": rincosStartDate, "endDate": rincosEndDate});
                      },
                      child: Text("搜尋")),
            ],
          ),
          Table(
            children: [
              tabRows([
                "G-market 交貨到 Rincos 日期\rPICK UP DATE",
                "櫃號\rCONTAINER NO.",
                "件數\rPCS",
                "仁川出船日期\rINCHEON ETD",
                "預計到港日期\rHKETA",
                "最快提櫃日\rREMARKS",
                "日期范围",
                "操作",
              ]),
              ...rincosData.map((e) => tabRowWidgets([
                    TextField(
                      decoration: const InputDecoration(border: OutlineInputBorder()),
                      controller: TextEditingController(text: e.pickUpDate ?? ""),
                      onChanged: (value) => e.pickUpDate = value.replaceAll("\r", ""),
                    ),
                    TextField(
                      decoration: const InputDecoration(border: OutlineInputBorder()),
                      controller: TextEditingController(text: e.containerNo ?? ""),
                      onChanged: (value) => e.containerNo = value.replaceAll("\r", ""),
                    ),
                    TextField(
                        decoration: const InputDecoration(border: OutlineInputBorder()),
                        controller: TextEditingController(text: e.pcs.toString()),
                        onChanged: (value) {
                          try {
                            String valueStr = value.toString().replaceAll("\r", "").toString();
                            e.pcs = int.parse(valueStr);
                          } catch (ex) {
                            e.pcs = 0;
                          }
                        }),
                    TextField(
                      decoration: const InputDecoration(border: OutlineInputBorder()),
                      controller: TextEditingController(text: e.incheonEtd ?? ""),
                      onChanged: (value) => e.incheonEtd = value.replaceAll("\r", ""),
                    ),
                    TextField(
                      decoration: const InputDecoration(border: OutlineInputBorder()),
                      controller: TextEditingController(text: e.hketa ?? ""),
                      onChanged: (value) => e.hketa = value.replaceAll("\r", ""),
                    ),
                    TextField(
                      decoration: const InputDecoration(border: OutlineInputBorder()),
                      controller: TextEditingController(text: e.remarks ?? ""),
                      onChanged: (value) => e.remarks = value.replaceAll("\r", ""),
                    ),
                    TextField(
                      decoration: const InputDecoration(border: OutlineInputBorder()),
                      controller: TextEditingController(text: e.dateRange ?? ""),
                      onChanged: (value) => e.dateRange = value,
                    ),
                    deleteIdData.contains(e.id.toString())
                        ? const Center(
                            child: CircularProgressIndicator(),
                          )
                        : TextButton(
                            onPressed: () {
                              if (e.id == null) {
                                rincosData.removeWhere((delElement) => delElement.id == e.id);
                                rincosCubit?.refresh();
                              } else {
                                rincosCubit?.delRincos(rincosId: e.id.toString());
                              }
                            },
                            child: Text("Del"),
                          )
                  ])),
            ],
          ),
          SizedBox(height: 10),
          Row(
            children: [
              SizedBox(width: 10),
              ElevatedButton(onPressed: () {}, child: Text("COPY")),
              SizedBox(width: 10),
              ElevatedButton(
                  onPressed: () {
                    rincosData.add(RincosBean.empty());
                    setState(() {});
                  },
                  child: Text("添加")),
              SizedBox(width: 10),
              saveLoading
                  ? CircularProgressIndicator()
                  : ElevatedButton(
                      onPressed: () {
                        // 遍历，如果为null 则直接赋值""
                        for (RincosBean rincosBean in rincosData) {
                          rincosBean.pickUpDate ??= " ";
                          rincosBean.containerNo ??= " ";
                          rincosBean.pcs ??= 0;
                          rincosBean.incheonEtd ??= " ";
                          rincosBean.hketa ??= " ";
                          rincosBean.remarks ??= " ";
                        }
                        rincosCubit?.saveRincos(rincosData: rincosData);
                      },
                      child: Text("保存")),
            ],
          ),
          SizedBox(height: 10),
        ],
      ),
    );
  }
}
